import axios from '../http/axios'
import './App.scss'
import React, { useEffect, useState, useRef } from 'react'
import { message} from 'antd'
import {
  Form,
  Input,
  Button,

} from 'antd-mobile'
import { useNavigate } from 'react-router'
export default function App() {
  const nav = useNavigate()
  const videoRef = useRef(null)
  const [faceCheck, setFaceCheck] = useState(false)
  const canvasRef = useRef(null)
  const [messageApi, contextHolder] = message.useMessage()
  //成功提示
  const success = (a) => {

    messageApi.open({
      type: 'success',
      content: a,
    })
  }
  //失败提示
  const error = (a) => {

    messageApi.open({
      type: 'error',
      content: a,
    });
  };
  const imageRef = useRef(null)

  const [video, setVideo] = useState()

  const [canvas, setCanvas] = useState()
  const notification = navigator.mediaDevices
  const [image, setImage] = useState('')
  const [faceLogin, setFaceLogin] = useState(true)
  const timer = useRef(null) // 
  const [img, setImg] = useState('')
  const [loginMode, setLoginMode] = useState('form') // 登录方式
  useEffect(() => {
    setCanvas(canvasRef.current)
    setVideo(videoRef.current)
    setImage(imageRef.current)
    if (video && faceLogin) {
      // 开启摄像头

      // 获取头像 base64，轮询调登录接口

    }
    if (!faceLogin) {
      timer.current && clearInterval(timer.current)
    }
    return () => {
      timer.current && clearInterval(timer.current)
    }
  }, [videoRef, video, faceLogin, canvas, canvasRef])
  // 打开摄像头
  const openMedia = () => {
    const constraints = {
      video: { width: 50, height: 50 },
      audio: false, // 音频不需要开启
    }
    //获得video摄像头
    if (
      navigator.mediaDevices === undefined ||
      navigator.mediaDevices.getUserMedia === undefined
    ) {
      // notification.error({
      //   message: '您的电脑暂不支持该功能，请使用其他方式登录',
      // })
      timer.current && clearInterval(timer.current)
      stopCapture()
      setFaceCheck(false) // 人脸识别失败
      setFaceLogin(false)  // 隐藏人脸识别登录界面
      setLoginMode('form') // 切换登录方式为账号密码
      return
    }
    const promise = navigator?.mediaDevices?.getUserMedia(constraints)
    promise
      .then((mediaStream) => {
        video.srcObject = mediaStream
        video.play()
      }
      )
  }

  //停止摄像机
  const stopCapture = () => {
    if (!video.srcObject) return
    const stream = video.srcObject
    const tracks = stream.getTracks()
    tracks.forEach((track) => {
      track.stop()
    })
  }
  // 获取头像的 base64，轮询调登录接口
  const getPhotoUrl = (() => {
    let num = 0
    timer.current = setInterval(async () => {
      num++
      const ctx = canvas.getContext('2d')

      ctx.drawImage(video, 0, 0, 500, 500)
      // toDataURL  ---  可传入'image/png'---默认, 'image/jpeg'
      const imgs = canvas.toDataURL() // img 是获取到的base64格式的字符串

      // 这里调接口 login(img) 
      // video.pause()
      // stopCapture()

      if (num >= 3) {
        clearInterval(timer.current)
        video.pause()
        stopCapture()


      }
      setImg(imgs)
    }, 2000)
  })
  const [flag, setflag] = useState(false)
  const login = () => {
    openMedia()
    getPhotoUrl()
    setflag(true)
  }
  const [username, setname] = useState('')
  const [password, setpassword] = useState('')

  const login1 = async () => {
    if (username || password) {
      if (img != '') {
        let { data: { msg } } = await axios.post('/regist', { username, account: username, password, face: img })
        success(msg)
        if (msg == '注册成功') {
          nav('/login')
        }
      } else {

        error('请录入人脸信息')
      }
    }



  }
  function Fromm() {
    return <Form
      className='login-form'
      layout='horizontal'
      footer={
        <span>


          <a style={{ fontSize: '12px', marginRight: '2.5rem' }} onClick={login}>录入人脸信息</a>

          <button  id='button'  type='submit' color='primary' size='large' style={{ marginTop: '10px' }} onClick={() => { login1() }}>
            注册
          </button>
        </span>
      }
    >

      <Form.Item
        name='name'
        label='用户名'
        rules={[{ required: true, message: '请输入用户名' }]}
      >
        <Input onChange={(e) => { setname(e); }} placeholder='请输入用户名' />
      </Form.Item>
      <Form.Item
        name='password'
        label='密码'
        rules={[{ required: true, message: '请输入密码' }]}
      >
        <Input onChange={(e) => { setpassword(e); }} placeholder='请输入密码' type='password'/>
      </Form.Item>
    </Form>
  }
  return (

    <div className='box1 animate__animated animate__bounce'>
      {contextHolder}
      <div className='shi'>
        
        <div style={{ color: 'theme.tc2', fontSize: 22, marginBottom: 15 }}>
          {/* {!faceCheck ? '人脸登录' : '认证失败，请重试'} */}
        </div>
        <video
          width='200px'
          height='200px'
          autoPlay
          ref={videoRef}
        ></video>
        <canvas
          ref={canvasRef}
          width='400px'
          height='400px'
          style={{ display: 'none' }}
        ></canvas>
        <img
          ref={imageRef}
          src=''
          alt='人脸识别'
          style={{ display: 'none' }}
        />
        {faceCheck ? (
          <div
            style={{
              position: 'absolute',
              top: 105,
              left: 20,
              height: 100,
              width: 100,
          
              display: 'flex',
              justifyContent: 'center',
              flexDirection: 'column',
              alignItems: 'center',
            }}
          >
            <button
              type='primary'
              style={{
                width: '120px'
,
                marginBottom: 15,
                background:'transparent',
              }}
              onClick={() => {
                setFaceCheck(false)
                openMedia()
                getPhotoUrl()
              }}
            >
              继续人脸识别
            </button>
          </div>
        ) : (
          ''
        )}
      </div>
      {Fromm()}
    </div>
  )
}

